package com.sayice.gomoku.service.impl;

import com.sayice.gomoku.dao.BoardDao;
import com.sayice.gomoku.dao.UserDao;
import com.sayice.gomoku.dao.impl.BoardDaoImpl;
import com.sayice.gomoku.dao.impl.UserDaoImpl;
import com.sayice.gomoku.pojo.User;
import com.sayice.gomoku.service.UserService;

/**
 * 用户业务
 */
public class UserServiceImpl implements UserService {
    private final UserDao userDao = new UserDaoImpl();
    private final BoardDao boardDao = new BoardDaoImpl();
    
    @Override
    public int register(User user) {
        return userDao.add(user);
    }
    
    @Override
    public User login(User user) {
        return userDao.queryByNameAndPassword(user.getName(), user.getPassword());
    }
    
    @Override
    public int setBoard(int userId, int boardId) {
        // 减少原来棋盘的使用数
        User user = getUserById(userId);
        boardDao.addUseCount(user.getBoardId(), -1);
        // 增加新棋盘使用数
        boardDao.addUseCount(boardId, 1);
        // 设置用户使用的棋盘
        return userDao.updateBoardId(userId, boardId);
    }
    
    @Override
    public int setDefaultBoard(int userId, int defaultBoardId) {
        // 增加棋盘使用数
        boardDao.addUseCount(defaultBoardId, 1);
        // 设置用户使用的棋盘
        return userDao.updateBoardId(userId, defaultBoardId);
    }
    
    @Override
    public int addPlayCount(int id) {
        return userDao.addPlayCount(id);
    }
    
    @Override
    public int addWinCount(int id) {
        return userDao.addWinCount(id);
    }
    
    @Override
    public boolean existsName(String name) {
        return userDao.queryByName(name) != null;
    }
    
    @Override
    public User getUserById(int id) {
        return userDao.queryById(id);
    }
    
    @Override
    public User getUserByName(String name) {
        return userDao.queryByName(name);
    }
}
